/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package android_serialport_api.sample;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import android_serialport_api.Get_Root;
import android_serialport_api.SerialPort;

import com.clouddot.baipai.infrastructure.environment.CrashHandler;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.ys.usbreader.UsbReader;
import android_serialport_api.SerialPortFinder;

public class application extends android.app.Application {

	public SerialPortFinder mSerialPortFinder = new SerialPortFinder();
	private SerialPort mSerialPort = null;
	private UsbReader mUsbReader = null;

	private static final String LOG_DIR = android.os.Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/BanPai/Log/";
	private static final String LOG_NAME = getCurrentDateString() + ".txt";
	private ArrayList<Activity> list = new ArrayList<Activity>();

	private String mDevice = "";
	private String mBaudrate = "-1";

	@Override
	public void onCreate() {
		super.onCreate();

//		ToastUtil.showToast(this, "检查网络中...");
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext());
		Environment env = Environment.createStaticInstance(application.this);
		env.context = application.this;

		env.initailNoException();

		getAndroiodScreenProperty();

		File dir = new File(LOG_DIR);
		if (!dir.exists()) {
			dir.mkdirs();
		}

	}
	/**
	 *
	 * 获取当前班牌的设备类型
	 */
	public void getAndroiodScreenProperty() {
		WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;         // 屏幕宽度（像素）
		int height = dm.heightPixels;       // 屏幕高度（像素）
		float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
		int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
		// 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
		int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
		int screenHeight = (int) (height / density);// 屏幕高度(dp)
		Handler handler = new Handler();

		if (screenWidth < 1000) {
			Env.getAppContext().itemCount = 15;
			Environment.getInstance().Height = 230;
		} else {
			Environment.getInstance().Height = 100;
			Env.getAppContext().itemCount = 11;
		}
	}

	@Override
	public void onTerminate() {
		// 程序终止的时候执行
		super.onTerminate();
	}

	public SerialPort getSerialPort(String path) throws SecurityException, IOException, InvalidParameterException {
		if (mSerialPort == null) {
			/* Read serial port parameters */
			 /* Read serial port parameters */
			//SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);
			//String path = sp.getString("DEVICE", "");
			//String path = "ttyS2";
			//String path = "/dev/ttyS3";//指定端口
			//int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
			int baudrate = 9600;//指定速率

			/* Check parameters */
			Log.e("application", "path:" + path + ", baudrate:" + baudrate);
			if ( (path.length() == 0) || (baudrate == -1)) {
				throw new InvalidParameterException();
			}

			/* Open the serial port */
			try {
				mSerialPort = new SerialPort(new File(path), baudrate, 0);
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), "出错了出错了出错了出错了", Toast.LENGTH_SHORT).show();
				Environment.getInstance().fileUtil.Errorinfo(e);
				e.printStackTrace();
			}
		}
		return mSerialPort;
	}


	public UsbReader getUsbReader() throws SecurityException, IOException, InvalidParameterException {
		if (mUsbReader == null) {
			try {
				mUsbReader = new UsbReader();
				String path = mUsbReader.getUsbReader();

				Get_Root root = new Get_Root();
				if( root.hasRoot()) {
					root.RootCmd("chmod 666 " + path);
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), "出错了出错了出错了出错了", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		}
		return mUsbReader;
	}


	public void closeSerialPort() {
		if (mSerialPort != null) {
			mSerialPort.close();
			mSerialPort = null;
		}
	}


	public void closeUsbReader() {
		if (mUsbReader != null) {
			mUsbReader.close();
			mUsbReader = null;
		}
	}


	Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {

		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			writeErrorLog(ex);
//			android.os.Process.killProcess(android.os.Process.myPid());
		}
	};

	/**
	  * 打印错误日志
	  * 
	  * @param ex
	  */
	protected void writeErrorLog(Throwable ex) {
		String info = null;
		ByteArrayOutputStream baos = null;
		PrintStream printStream = null;
		try {
			baos = new ByteArrayOutputStream();
			printStream = new PrintStream(baos);
			ex.printStackTrace(printStream);
			byte[] data = baos.toByteArray();
			info = new String(data);
			data = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (printStream != null) {
					printStream.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.d("example", "崩溃信息\n" + info);
		File dir = new File(LOG_DIR);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, LOG_NAME);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file, true);
			fileOutputStream.write(info.getBytes());
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


	/**
	  * 获取当前日期
	  * 
	  * @return
	  */
	private static String getCurrentDateString() {
		String result = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
				Locale.getDefault());
		Date nowDate = new Date();
		result = sdf.format(nowDate);
		return result;
	}

	public void setDevice (String device) {
		this.mDevice = device;
	}

	public void setBaudrate(String baudrate) {
		this.mBaudrate = baudrate;
	}

}
